<template>
  <li class="t-treeItem">
    <div class="node-arrow">
      <span v-if="isFolder" @click="toggle">
        <van-icon v-if="!expanded" name="arrow" />
        <van-icon v-else name="arrow-down" />
      </span>
      <label v-if="!isFolder || !checkbox" class="checkboxLabel">
        <van-checkbox
          @click="checkboxChange"
          shape="shape"
          icon-size="0.4rem"
          :name="item[valueName]" 
        >
          {{item[labelName]}}
        </van-checkbox>
      </label>
      <label v-else class="checkboxLabel">
        <div @click="checkboxChange('all')" role="checkbox" class="van-checkbox self" aria-checked="false">
          <div class="van-checkbox__icon van-checkbox__icon--shape" :class="{'van-checkbox__icon--checked':checkedFather.indexOf(item[valueName])!=-1}" style="font-size: 0.4rem;">
            <i class="van-badge__wrapper van-icon van-icon-success"></i>
          </div>
          <span class="van-checkbox__label">{{item[labelName]}}</span>
        </div>
      </label>
    </div>
    <ul v-show="expanded" v-if="isFolder">
      <item 
        v-for="(child,index) in item.children" 
        :item='child' 
        :key='index'
        :label-name="labelName" 
        :value-name="valueName" 
        :checkbox="checkbox"
        :open="open"
      />
    </ul>
  </li>
</template>

<script lang="ts">
import { defineComponent ,reactive,toRefs,computed,inject} from 'vue'

export default defineComponent({
  name:'tTreeItem',
  emits:['change'],
  props: ['labelName','valueName','item','checkbox','open'],
  setup (props) {
    const checked:Array<any> = inject('checked') || [];
    const checkedFather:Array<any> = inject('checkedFather') || [];
    const deleteFatherId:Function = inject('deleteFatherId') || (()=>{});
    const addFatherId:Function = inject('addFatherId') || (()=>{});
    const treeFun:Function = inject('treeFun') || (()=>{});
    const data = reactive({
      expanded: props.open
    })
    const isFolder = computed(()=>props.item.children && props.item.children.length>0);
    
    return {
      ...toRefs(data),
      isFolder,
      checkedFather,
      checked,
      toggle(){
        data.expanded = !data.expanded
      },
      checkboxChange(type){
        if(!props.checkbox){
          checked.splice(0);
          checked.push(props.item[props.valueName]);
        }else{
          let state = checked.indexOf(props.item[props.valueName]) == -1;
          if(type == 'all'){
            state = checkedFather.indexOf(props.item[props.valueName]) == -1;
          }
          treeFun(props.item,state)
          if(state){
            addFatherId(props.item[props.valueName])
          }else{
            deleteFatherId(props.item[props.valueName])
          }
        }
      }
    }
  }
})
</script>

<style lang="scss">
.t-treeItem{
  padding-left: 0.38rem;
}
</style>